package com.grantz.function.bbs.core.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.grantz.function.bbs.core.entity.CommentChild;
import com.grantz.function.bbs.core.inter.CommentChildService;
import com.grantz.function.bbs.core.jpa.CommentChildJPA;
import com.grantz.model.bbs.CommentChildModel;
import com.grantz.model.bbs.CommentChildSearch;
import com.grantz.models.base.element.page.ElementPage;
@Service
public class CommentChildServiceImpl implements CommentChildService {
	
	@Autowired
	private CommentChildJPA dao;

	@Override
	public CommentChild save(CommentChild entity) {
		return dao.save(entity);
	}

	@Override
	public Optional<CommentChild> findOneById(String id) {
		return dao.findById(id);
	}

	@Override
	public ElementPage<CommentChildModel> queryElementPage(CommentChildSearch query) throws Exception {
		Page<CommentChild>  page = queryPage(query);
		return new ElementPage<CommentChildModel>(popList(page.getContent()), page.getTotalElements(), page.getNumber(), page.getSize());
	}
	
	private  List<CommentChildModel>  popList(List<CommentChild>  entityList){
		List<CommentChildModel>  rt = new ArrayList<CommentChildModel>();
		CommentChildModel  model = null ;
		for(CommentChild  entity : entityList) {
			  model =  new CommentChildModel();
			  model.setId(entity.getId());
			  rt.add(model);
		}
		return rt;
	}

	@Override
	public Page<CommentChild> queryPage(CommentChildSearch model) throws Exception {
		PageRequest pageable = PageRequest.of(model.getPageNo(), model.getPageSize());
		Specification<CommentChild> specifications = new Specification<CommentChild>() {

			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<CommentChild> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> list = new ArrayList<Predicate>();
//				if(StringUtil.isNotEmpty(model.getWechatno())) {
//					Predicate pred = criteriaBuilder.like(root.get("wechatNo").as(String.class), "%"+model.getWechatno()+"%");
//					list.add(pred);
//				}
				Predicate[] p = new Predicate[list.size()];
				return criteriaBuilder.and(list.toArray(p));
			}
		};
		return dao.findAll(specifications, pageable);
	}

}
